import { Module } from "vuex"
import { RootState } from "../index"
import { UserState } from "./user"
import http from "@/utils/http"
import { ElMessage } from "element-plus"
const state = {
  id: 0,
  name: "",
  oldContent: "",
  content: "",
  editable: false,
  parentId: null as null | number,
  user: {} as UserState,
  occupyUser: null as UserState | null,
}
const originalState = { ...state }
export type MarkdownState = typeof state

export const store: Module<MarkdownState, RootState> = {
  namespaced: true,
  state,
  mutations: {
    setMarkdown(state: MarkdownState, markdown: MarkdownState) {
      for (const i in state) {
        state[i] = markdown[i]
      }
      state.oldContent = state.content
    },
    setOccupyUser(
      state: MarkdownState,
      occupyUser: MarkdownState["occupyUser"]
    ) {
      state.occupyUser = occupyUser
    },
    clearOccupyUser(state: MarkdownState) {
      state.occupyUser = null
    },
    clearMarkdown(state: MarkdownState) {
      for (const i in state) {
        state[i] = originalState[i]
      }
    },
    changeContent(state: MarkdownState, content: string) {
      state.content = content
    },
  },
  actions: {
    async saveDoc({ commit, state }) {
      const res = await http.post("/file/updateMarkdown", {
        id: state.id,
        content: state.content,
      })
      if (res.code === 1) {
        commit("setMarkdown", state)
        ElMessage.success("保存成功")
      } else {
        ElMessage.success("保存失败")
      }
    },
  },
}
